#!/usr/bin/env python

import elementtree.ElementTree as ET
import types

class config:
   def __init__(self, filename="config.xml", debug=False):
      self.tree = ET.parse(filename)
      self.debug = debug

   def __find(self, name):
      try:
         (path, attribute) = name.split("#")
      except ValueError:
         path = name
         attribute = ""
      if (attribute==""):
         return self.tree.findtext(path)
      elif (attribute=="node"):
         return self.tree.find(path)
      elif (attribute=="children"):
         children = self.tree.find(path).getchildren()
         return map(lambda x: "%s/%s" % (path, x.tag), children)
      else:
         element = self.tree.find(path)
         return element.attrib[attribute]

   def __getitem__(self, key):
      try:
         value = self.__find(key)
         if type(value) == types.StringType:
            return value.encode("ASCII")
         return value
      except:
         if self.debug: raise
         return None

   def GetInterval(self, name):
      day    = self["%s#day" % name]
      hour   = self["%s#hour" % name]
      minute = self["%s#minute" % name]
      second = self["%s#second" % name]

      interval = 0
      if (day):
         interval += int(day)*86400
      if (hour):
         interval += int(hour)*3600
      if (minute):
         interval += int(minute)*60
      if (second):
         interval += int(second)

      if interval == 0:
         raise Exception()

      return interval

if __name__ == "__main__":
   x = config("test.xml")

   processors = x['processors#node']
   for child in processors.getchildren():
      processor_name = child.attrib['type']
      print processor_name

   assert(x['source#type']=='flip_flop_ps')
   assert(x['source/picture1']=='picture1.jpg')
   assert(x['source/picture2']=='picture2.jpg')
   assert(x['intervals/rollup#day']=='1')
   assert(x['intervals/frame#minute']=='1')
   assert(x['directories/rollup']=='./movies')
   assert(x['directories/frame']=='./frames')
   assert(x.GetInterval("intervals/rollup")==86400)
   assert(x.GetInterval("intervals/frame")==60)

